package com.thingsgrid.basicInterface.service;

import com.sun.net.httpserver.HttpServer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheus.PrometheusConfig;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

@Configuration
public class prometheusService {


	public PrometheusMeterRegistry getPrometheusRegistry(){
		PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);

		try {
			HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
			server.createContext("/prometheus", httpExchange -> {
				String response = prometheusRegistry.scrape();
				httpExchange.sendResponseHeaders(200, response.getBytes().length);
				try (OutputStream os = httpExchange.getResponseBody()) {
					os.write(response.getBytes());
				}
			});

			new Thread(server::start).start();
		} catch (
			IOException e) {
			throw new RuntimeException(e);
		}
		return prometheusRegistry;
	}


	@Bean
	MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
		// return registry -> registry.config().commonTags("application", "MYAPPNAME");
		return registry -> registry.config().commonTags("APPNAME", "thingsgrid-basicInterface","CASE","thingsgrid-basicInterface_1");
	}

}
